const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
const Promise = function(executor){
	if(!(executor instanceof Function)){
		throw "executor类型错误！"
	}
	this.state = PENDING;// 状态
	this.result = undefined;// 状态值
	// 更改状态为fulfilled,成功值为value
	const _onResolve =function(value){
		// 如果状态被更改，那么不允许执行后续代码（状态只允许更改一次）
		if(this.state !== PENDING) return;
		this.state = FULFILLED;
		this.result = value;
	}
	// 更改状态为rejected,失败的值为value
	const _onReject = function(value){
		if(this.state !== PENDING) return;
		this.state = REJECTED;
		this.result = value;
	}
	try{
		// 调用执行器函数
		executor(_onResolve.bind(this),_onReject.bind(this));
	}catch (value){
		// _onReject.bind(this,value)();
		_onReject.call(this,value)
	}
	
};
Object.assign(Promise.prototype,{
	// onResolved:成功回调
	// onRejected:失败回调
	then(onResolved,onRejected){
		// this指向的是Promise实例p
		// 当状态为成功时，调用成功回调,传递成功值
		if(this.state === FULFILLED){
			onResolved(this.result);
		}else if(this.state == REJECTED){
			onRejected(this.result);
		}
	},
	catch(){
	
	}
});
export default Promise;